package com.nbjtjc.safe.aspect;

import com.nbjtjc.safe.Exception.SafeException;
import com.nbjtjc.safe.annotation.DataFilter;
import com.nbjtjc.safe.bean.Constant;
import com.nbjtjc.safe.model.sys.SysUser;
import com.nbjtjc.safe.service.sys.SysDeptService;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @auther guqianbin
 * @date 2018/8/10 10:19
 **/
@Aspect
@Component
public class DataFilterAspect {
    @Autowired
    private SysDeptService sysDeptService;

    @Pointcut("@annotation(com.nbjtjc.safe.annotation.DataFilter)")
    public void dataFilterCut() {

    }

    @Before("dataFilterCut()")
    public void dataFilter(JoinPoint point) throws Throwable {
        Object filterSql = point.getArgs()[0];

        SysUser user = MyShiroUtils.getSessionUser();

        //如果不是超级管理员，则只能查询本部门及子部门数据
        if (user.getUserId() != Constant.SUPER_ADMIN) {
            filterSql=getFilterSQL(user, point);
        } else {
            filterSql="";

        }
        return;

    }

    /**
     * 获取数据过滤的SQL
     */
    private String getFilterSQL(SysUser user, JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        DataFilter dataFilter = signature.getMethod().getAnnotation(DataFilter.class);
        //获取表的别名
        String tableAlias = dataFilter.tableAlias();
        if (StringUtils.isNotBlank(tableAlias)) {
            tableAlias += ".";
        }
        StringBuilder filterSql = new StringBuilder();
        List<Integer> companyIds = new ArrayList<>();
        companyIds.add(MyShiroUtils.getCompanyId());
        filterSql.append(tableAlias).append("company_id in(");
        for (int i = 0; i < companyIds.size(); i++) {
            filterSql.append(companyIds.get(i));
        }
        filterSql.append(")");

        return filterSql.toString();
    }
}
